package com.md24housecall.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.md24housecall.adapter.MultiIHealthAdapter;
import com.md24housecall.adapter.MultiIHealthAdapter.OnDeleteListener;
import com.md24housecall.manager.CacheManager;
import com.md24housecall.manager.DimenManager;
import com.md24housecall.model.UserAccountIHealth;
import com.md24housecall.net.UrlBuilder;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;
import com.md24housecall.view.PagingListView;
import com.md24housecall.view.RatioImageView;
import com.md24housecall.view.RatioRelativeLayout;
import com.md24housecall.view.PagingListView.PagingListViewListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class PatientIHealthActivity extends Activity implements OnItemClickListener,PagingListViewListener{
	private Button btnBack;
	private PagingListView lvMultiAccount;
	private GlobalConstant constant=GlobalConstant.getInstance();
	private Utils util=Utils.getInstance();
	private AQuery mAQuery;
	private ProgressBar mProgressBar;
	private CacheManager cacheManager;
	private MultiIHealthAdapter adapter;
	private List<UserAccountIHealth> listUser=new ArrayList<UserAccountIHealth>();
	private String multiAccountUrl="";
	private Button btnAddAccount;
	private int mIHealtPosition=0;
	private RatioImageView mImgHeader;
	private RatioRelativeLayout relBackground;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_patient_ihealth);
		relBackground=(RatioRelativeLayout)findViewById(R.id.relBackground);
		relBackground.setRatio(DimenManager.WIDTH_BACKGROUND_PATIENT,
				DimenManager.HEIGHT_BACKGROUND_PATIENT);
		mImgHeader = (RatioImageView)findViewById(R.id.imgHeader);
		mImgHeader.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		mAQuery=new AQuery(this);
		btnBack = (Button) findViewById(R.id.btnBack);
		mIHealtPosition=getIntent().getIntExtra(constant.PATIENT_IHEALTH_POSITION_KEY, 0);
		multiAccountUrl=String.format(UrlBuilder.URL_GET_PATIENT, util.getPreferenceString(constant.KEYUSERID, this, ""));
		mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
		cacheManager = CacheManager.getInstance(this);
		btnAddAccount=(Button)findViewById(R.id.btnAddAccount);
		btnAddAccount.setVisibility(View.INVISIBLE);
		lvMultiAccount=(PagingListView)findViewById(R.id.lvIhealthAccount);
		lvMultiAccount.setPullLoadEnable(false);
		lvMultiAccount.setPullRefreshEnable(true);
		lvMultiAccount.setOnItemClickListener(this);
		lvMultiAccount.setPagingListViewListener(this);
		btnAddAccount.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
		btnBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});
	}

	private void confirmDelete(final int position){
	      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
	      alertDialogBuilder.setMessage(R.string.msg_ihealth_delete_confirm);
	      alertDialogBuilder.setPositiveButton(R.string.button_yes, 
	      new DialogInterface.OnClickListener() {
			
	         @Override
	         public void onClick(DialogInterface arg0, int arg1) {
				mAQuery.ajax(String.format(UrlBuilder.URL_DELETE_IHEALTH_ACCOUNT, listUser.get(position).getIhealthId(),util.getCode(PatientIHealthActivity.this)),String.class,new AjaxCallback<String>(){
					@Override
					public void callback(String url, String object,
							AjaxStatus status) {
						// TODO Auto-generated method stub
						super.callback(url, object, status);
						android.util.Log.d(GlobalConstant.TAG, "result delete: "+object);
						if(status.getCode()==200){
							if(mProgressBar.getVisibility()==View.GONE)
								mProgressBar.setVisibility(View.VISIBLE);
							refreshListUser();
						}
					}
				});
	         }
	      });
	      alertDialogBuilder.setNegativeButton(R.string.button_no, 
	      new DialogInterface.OnClickListener() {
				
	         @Override
	         public void onClick(DialogInterface dialog, int which) {
	            
			 }
	      });
		    
	      AlertDialog alertDialog = alertDialogBuilder.create();
	      alertDialog.show();
		    
	   }
	
	private void refreshListUser(){
		mAQuery.ajax(multiAccountUrl, JSONObject.class, new AjaxCallback<JSONObject>(){
			@Override
			public void callback(String url, JSONObject object, AjaxStatus status) {
				if(mProgressBar.getVisibility()==View.VISIBLE)
					mProgressBar.setVisibility(View.GONE);
				lvMultiAccount.stopRefresh();
				if(status.getCode()==200){
					JSONArray jsonArray=null;
					try {
						jsonArray=object.getJSONArray("patients");
						int len = jsonArray.length();
						if(len>0){
							JSONObject json_data=jsonArray.getJSONObject(mIHealtPosition).getJSONObject("ihealth_token");
							lvMultiAccount.setVisibility(View.VISIBLE);
	//						txvNoData.setVisibility(View.GONE);
							if(listUser!=null && listUser.size()>0)
								listUser.clear();
							UserAccountIHealth user=new UserAccountIHealth();
							user.setId(json_data.getString("id"));
							user.setToken(json_data.getString("token"));
							user.setCode(json_data.getString("code"));
							user.setIhealthId(json_data.getString("ihealth_id"));
							user.setUserInfo(json_data.getString("user_info"));
							listUser.add(user);
							MyLog.d(GlobalConstant.TAG, "tokent patient ihealth: "+user.getToken());
							if(adapter==null){
								adapter=new MultiIHealthAdapter(PatientIHealthActivity.this, listUser);
								adapter.setButtonDelete(false);
								adapter.setOnDeleteListener(new OnDeleteListener() {
									
									@Override
									public void onDeleteComplete(int position) {
										// TODO Auto-generated method stub
										android.util.Log.d(GlobalConstant.TAG,"position: "+position);
										confirmDelete(position);
									}
								});
								lvMultiAccount.setAdapter(adapter);
							}else{
								adapter.notifyDataSetChanged();
							}
						}else{
							lvMultiAccount.setVisibility(View.INVISIBLE);
	//						txvNoData.setVisibility(View.VISIBLE);
						}
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}else{
					lvMultiAccount.setVisibility(View.VISIBLE);
					Toast.makeText(PatientIHealthActivity.this, status.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(constant.isUpdateIhealthUser){
			constant.isUpdateIhealthUser=false;
			if(mProgressBar.getVisibility()==View.GONE)
				mProgressBar.setVisibility(View.VISIBLE);
			refreshListUser();
		}
	}
	
	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		refreshListUser();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		cacheManager.clearActivityReportData();
		cacheManager.clearBloodOxygenData();
		cacheManager.clearBloodPressureData();
		cacheManager.clearGlucoData();
		cacheManager.clearWeightData();
		JSONObject object;
		Intent intent=new Intent(this,IHealthActivity.class);
		try {
			object = new JSONObject(listUser.get(position-1).getToken());
			util.savePreferenceString(constant.USERID_IHEALTH_KEY, this, object.getString("UserID"));
			util.savePreferenceString(constant.ACCESSTOKEN_IHEALTH_KEY, this, object.getString("AccessToken"));
			util.savePreferenceString(constant.REFRESHTOKEN_IHEALTH_KEY, this, object.getString("RefreshToken"));
			JSONObject userInfo=new JSONObject(listUser.get(position-1).getUserInfo());
			MyLog.d(GlobalConstant.TAG,"userInfo: "+userInfo.toString());
			intent.putExtra(constant.IHEALTH_NAME_KEY, userInfo.getString("nickname"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		startActivity(intent);
	}
}
